using System;
using System.Collections.Generic;
using UnityEngine.Networking;
using System.Collections;
using System.Text;
using ZyGame.Execute;

namespace ZyGame.Transport
{
    public static class WebService
    {
        public static void UploadData(string url, byte[] bytes)
        {
        }

        public static Runnable<byte[]> DownloadAssetBytes(string url)
        {
            if (Client.Running.TryGetOrCreate(url, out Runnable<byte[]> executedBuilder))
            {
                return executedBuilder;
            }

            IEnumerator Runnable()
            {
                using UnityWebRequest request = UnityWebRequest.Get(url);
                yield return request.SendWebRequest();
                if (request.result != UnityWebRequest.Result.Success)
                {
                    Client.Console.WriteLine("download failurefuly:" + url);
                    executedBuilder.SetResult(new Exception(request.error));
                    yield break;
                }

                if (executedBuilder == null)
                {
                    yield break;
                }

                Client.Console.WriteLine("download completed:" + url);
                executedBuilder.SetResult(request.downloadHandler.data);
            }

            executedBuilder.Execute(Runnable);
            return executedBuilder;
        }

        public static Runnable<string> Post(string url, string body, string header)
        {
            WebRequest request = CreateRequest(url, WebMethod.POST);
            if (header.IsNullOrEmpty() is false)
            {
                List<Header> items = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Header>>(header);
                if (items is not null && items.Count > 0)
                {
                    items.ForEach(x => request.SetHeadder(x.key, x.value));
                }
            }

            request.UploadData(UTF8Encoding.UTF8.GetBytes(body));
            return request.OnStart();
        }


        public static Runnable<string> Get(string url, string header)
        {
            WebRequest request = CreateRequest(url, WebMethod.GET);
            if (header.IsNullOrEmpty() is false)
            {
                List<Header> items = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Header>>(header);
                if (items is not null && items.Count > 0)
                {
                    items.ForEach(x => request.SetHeadder(x.key, x.value));
                }
            }

            return request.OnStart();
        }

        public static WebRequest CreateRequest(string url, WebMethod method) => new WebRequest(url, method);
    }
}